package com.mayundev.pa.service;

import com.mayundev.pa.model.FileNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class FileService {

    @Value("${file.base-path:files/20250312}")
    private String basePath;

    // 添加文件大小限制（默认10MB）
    @Value("${file.max-size:10485760}")
    private long maxFileSize;

    // 添加文件比较器
    private static final Comparator<FileNode> FILE_COMPARATOR = (f1, f2) -> {
        // 首先按类型排序（目录在前）
        if (f1.isDirectory() != f2.isDirectory()) {
            return f1.isDirectory() ? -1 : 1;
        }
        // 然后按名称排序（不区分大小写）
        return f1.getName().compareToIgnoreCase(f2.getName());
    };

    public List<FileNode> getFileTree() {
        File root = new File(basePath);
        if (!root.exists() || !root.isDirectory()) {
            return new ArrayList<>();
        }
        return buildFileTree(root);
    }

    private List<FileNode> buildFileTree(File directory) {
        List<FileNode> nodes = new ArrayList<>();
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                FileNode node = new FileNode();
                node.setName(file.getName());
                node.setPath(file.getPath());
                node.setDirectory(file.isDirectory());

                if (file.isDirectory()) {
                    node.setChildren(buildFileTree(file));
                }

                nodes.add(node);
            }

            // 对节点列表进行排序
            nodes.sort(FILE_COMPARATOR);
        }

        return nodes;
    }

    /**
     * 获取文件内容
     * @param path 文件路径
     * @return 文件内容
     * @throws RuntimeException 如果文件读取失败
     * @throws IllegalArgumentException 如果路径不合法
     */
    public String getFileContent(String path) {
        log.debug("Attempting to read file content from path: {}", path);
        try {
            // 1. 路径规范化
            Path normalizedFullPath = Paths.get(path).normalize().toAbsolutePath();

            // 2. 文件存在性检查
            if (!Files.exists(normalizedFullPath)) {
                throw new IllegalArgumentException("File does not exist: " + path);
            }

            // 3. 文件类型检查
            if (!Files.isRegularFile(normalizedFullPath)) {
                throw new IllegalArgumentException("Path is not a regular file: " + path);
            }

            // 4. 文件大小检查
            if (Files.size(normalizedFullPath) > maxFileSize) {
                throw new IllegalArgumentException(
                    String.format("File size exceeds limit of %d bytes", maxFileSize)
                );
            }

            // 5. 文件读取
            return Files.readString(normalizedFullPath);

        } catch (IOException e) {
            log.error("Failed to read file: {}", path, e);
            throw new RuntimeException("Failed to read file: " + e.getMessage(), e);
        }
    }
}
